package org.riahispano.twitterds.services.impl;


import org.apache.log4j.Logger;
import org.riahispano.twitterds.domain.LastMessage;
import org.riahispano.twitterds.domain.Status;
import org.riahispano.twitterds.services.TwitterTimeLineService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.flex.remoting.RemotingDestination;
import org.springframework.flex.remoting.RemotingInclude;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;
import twitter4j.Paging;
import twitter4j.Twitter;
import twitter4j.TwitterException;

import javax.jms.Queue;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: ecamacho
 * riahispano 2010
 */
@Service("twitterTimeLineService")
@RemotingDestination( channels={"my-amf"})
public class TwitterTimeLineServiceImpl implements TwitterTimeLineService {

    private static final Logger logger = Logger.getLogger( TwitterTimeLineServiceImpl.class.getName() );

    @Autowired
    private JmsTemplate jmsTemplate;

    @Autowired
    private Queue queue;

    @RemotingInclude
    public List<Status> getFriendsTimeline(String user, String password, int page) {
        	logger.debug("[getFriendsTimeline]");
		Twitter twitter = new Twitter( user, password );
		Paging paging = new Paging( page );
		List<Status> statuses = null;

		try {
			statuses = transformStatus( twitter.getFriendsTimeline( paging ) );
			if( statuses.size() > 0 )
			{
				sendMessage(user, password, getLastMessageId( statuses) );
			}
		} catch (TwitterException e) {
			logger.error( "[Error getting friends timeline]", e );
		}

		return statuses;
    }

    public List<Status> getUserTimeline(String user, String password, int page) {
        Twitter twitter = new Twitter( user, password );
		Paging paging = new Paging( page );
		List<Status> statuses = null;

		try {
			statuses = transformStatus( twitter.getUserTimeline( paging ) );
		} catch (TwitterException e) {
			logger.error( "[Error getting user timeline]", e );
		}

		return statuses;
    }

    public List<Status> getFriendsTimelineSinceId(String user, String password, long lastId) {
        logger.debug("[getFriendsTimelineSinceId]");
		Twitter twitter = new Twitter( user, password );

		List<Status> statuses = null;

		try {
			Paging paging = new Paging( lastId );

			statuses = transformStatus( twitter.getFriendsTimeline( paging ) );

			//There are new messages, we collect the first 20 again
			if( statuses.size() > 0 )
			{
				paging   = new Paging( 1, lastId );
				statuses = transformStatus( twitter.getFriendsTimeline( paging ) );
			}
			else
			{
				statuses = null;
			}
		} catch (TwitterException e) {
			logger.error( "[Error getting friends timeline]", e );
		}

		return statuses;
    }

    public long getLastMessageId( List<Status> statuses )
	{

		return statuses.get( statuses.size() -1 ).getId();
	}

	private void sendMessage( final String user, final String password, final long lastId)
	{

        jmsTemplate.convertAndSend( queue, new LastMessage( user, password, lastId ) );

	}

	private List<Status> transformStatus( List<twitter4j.Status> sourceStatuses )
	{
		List<Status> statuses = new ArrayList<Status>( sourceStatuses.size() );
		for( twitter4j.Status sourceStatus :  sourceStatuses )
		{
			Status status = new Status( );
			BeanUtils.copyProperties( sourceStatus, status );
			status.setUsername( sourceStatus.getUser().getScreenName() );
			status.setProfileImageURL( sourceStatus.getUser().getProfileImageURL().toString() );
			statuses.add( status );
		}
		return statuses;
	}
}
